package com.clkj.mobileinspector.ui.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.pm.SigningInfo;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.MapView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.clkj.mobileinspector.R;
import com.clkj.mobileinspector.model.Constant;
import com.clkj.mobileinspector.model.ObserverOnNext;
import com.clkj.mobileinspector.model.OkHttpUtils;
import com.clkj.mobileinspector.model.bean.LogResultBean;
import com.clkj.mobileinspector.model.bean.MainBean;
import com.clkj.mobileinspector.model.bean.QueryBean;
import com.clkj.mobileinspector.model.bean.QuerySuccessBean;
import com.clkj.mobileinspector.model.bean.ResourceApi;
import com.clkj.mobileinspector.model.bean.UserBean;
import com.clkj.mobileinspector.ui.adapter.MainActivityAdapter;
import com.clkj.mobileinspector.utils.JsonUtils;
import com.clkj.mobileinspector.utils.RandomStringUtils;
import com.clkj.mobileinspector.utils.ResourceApiUtils;
import com.clkj.mobileinspector.utils.SignCheckUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lws.basic.base.BaseActivity;
import com.lws.basic.utils.common.GsonUtils;
import com.lws.basic.utils.common.MyLogger;
import com.lws.basic.utils.common.MyToast;
import com.lws.basic.utils.common.RxUtils;
import com.lws.basic.utils.common.SharePreferenceUtils;
import com.lws.basic.utils.common.TimeUtils;
import com.xdja.reckon.ReckonAgent;
import com.xdja.reckon.function.StateListener;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

//移动督察
@RuntimePermissions
public class MainActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {

    @BindView(R.id.tv)
    TextView mTv;
    @BindView(R.id.rv_menu)
    RecyclerView mRvMenu;
    public static List<ResourceApi> resourceApiList = new ArrayList<>();

    private MainActivityAdapter mMainActivityAdapter;
    private LoginBroadcastReceiver mReceiver;
    @Override
    public int setLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initData() {
        super.initData();
        ButterKnife.bind(this);
        MainActivityPermissionsDispatcher.permissionWithCheck(this);
        receiver();
        initMenu();
        getResourceAddress();
        log();
        reckonAgent();




   }




    /**
     * 菜单
     */
    private void initMenu() {
        List list = new ArrayList();
//        list.add(new MainBean(R.mipmap.menu1, "现场督察"));
//        list.add(new MainBean(R.mipmap.menu2, "汇总分析"));
       //  list.add(new MainBean(R.mipmap.menu3, "图表分析"));
        list.add(new MainBean(R.mipmap.menu4, "民警维权"));
        list.add(new MainBean(R.mipmap.menu5, "维权查询"));
        mRvMenu.setLayoutManager(new GridLayoutManager(this, 3));
        mMainActivityAdapter = new MainActivityAdapter(list);
        mMainActivityAdapter.setOnItemClickListener(this);
        mRvMenu.setAdapter(mMainActivityAdapter);

    }



    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        MainBean mainBean = (MainBean) adapter.getData().get(position);
        switch (mainBean.getIcon()) {
            case R.mipmap.menu1://现场督察
                startActivity(new Intent(this, InspectorRecordActivity.class));
                break;
            case R.mipmap.menu2://汇总分析
                startActivity(new Intent(this, StatisticsActivity.class));

                break;
            case R.mipmap.menu3:
                break;
            case R.mipmap.menu4://民警维权
                startActivity(new Intent(this, SafeguardRightsActivity.class));
                break;
            case R.mipmap.menu5://维权查询
                startActivity(new Intent(this, SafeguardRightsRecordActivity.class));

                break;
        }
    }

    /**
     * 获取文件写入权限
     */

    @NeedsPermission({Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.READ_PHONE_STATE})
    void permission() {
    }

    /**
     * 权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 应用统计
     */
    public void reckonAgent() {
        try {
            String user = SharePreferenceUtils.getString(MainActivity.this, Constant.userCredential, "");
            UserBean userBean = GsonUtils.getInstance().fromJson(user, UserBean.class);
            ReckonAgent.getInstance(this)
                    .config("20.20.1.40", "8090")
                    .startAnalytics(userBean.getCredential().getLoad().getUserInfo().getUserId())
                    .addStateListener(new StateListener() {
                        @Override
                        public void reportState(String state) {
                            MyLogger.i("应用统计：" + state);
                        }
                    });
        } catch (Exception e) {
            MyLogger.i("应用统计报错： " + e.getMessage());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ReckonAgent.getInstance(this).stopAnalytics();
        unregisterReceiver(mReceiver);
    }

    /**
     * 日志登录
     */
    private void log() {
        MyLogger.i("日志登录");
        Map<Object, Object> map = new HashMap<>();
        map.put("username", "admin");
        map.put("password", "111111");
        OkHttpUtils.post(Constant.logLogin, new JSONObject(map).toString(), LogResultBean.class).compose(this.bindToLifecycle()).subscribe(new ObserverOnNext<LogResultBean>() {
            @Override
            public void onNext(LogResultBean logResultBean) {
                if (logResultBean.getCode().equals("1")) {
                    SharePreferenceUtils.putString(MainActivity.this, "token", logResultBean.getResult());
                    MyLogger.i("日志登录成功");
                } else {
                    SharePreferenceUtils.putString(MainActivity.this, "token", "");

                    MyLogger.i(logResultBean.getMessage());
                }
            }
        });

    }

    /**
     * 资源服务寻址
     */
    private void getResourceAddress() {
        try {
            showLoading();
            Observable.create(new ObservableOnSubscribe<Bundle>() {
                @Override
                public void subscribe(ObservableEmitter<Bundle> emitter) throws Exception {
                    Thread.sleep(1000);
                    String appCredential = SharePreferenceUtils.getString(MainActivity.this, Constant.appCredential, "");
                    String version = SharePreferenceUtils.getString(MainActivity.this, "version", "1");
                    MyLogger.i("寻址");
                    Uri uri = Uri.parse("content://com.ydjw.rsb.getResourceAddress");
                    String messageId = RandomStringUtils.getRandomString(32);//32位随机字符串
                    ContentResolver contentResolver = getContentResolver();
                    Bundle bundle = new Bundle();
                    bundle.putString("appCredential", appCredential);
                    bundle.putString("version", version);
                    bundle.putString("messageId", messageId);
                    MyLogger.i("寻址参数：" + bundle.toString());

                    Bundle callBack = contentResolver.call(uri, "", "", bundle);
                    emitter.onNext(callBack);
                }
            }).compose(RxUtils.io_main()).compose(this.bindToLifecycle()).subscribe(new ObserverOnNext<Bundle>() {
                @Override
                public void onNext(Bundle callBack) {
                    dismissLoading();
                    if (callBack != null) {
                        int version = callBack.getInt("version");
                        String messageId = callBack.getString("messageId");
                        String message = callBack.getString("message");
                        int resultCode = callBack.getInt("resultCode");//0 成功40000服务内部错误 40001入参不完整 40002 应用凭证认证失败 41000
                        String resourceList = callBack.getString("resourceList");//资源列表
                        MyLogger.i("寻址返回值");
                        MyLogger.i("resourceList" + resourceList);
                        MyLogger.i("resultCode:" + resultCode);
                        MyLogger.i("message:" + message);
                        MyLogger.i("version:" + version);
                        MyLogger.i("messageId:" + messageId);

                        if (resultCode == 0) {
                            //寻址json 转实体类
                            Gson gson = new Gson();
                            Type type = new TypeToken<List<ResourceApi>>() {
                            }.getType();
                            resourceApiList = gson.fromJson(resourceList, type);

                            //获取用户凭证
                            getData(null);
                        } else {
                            MyToast.show(resultCode + message);
                        }
                        //40002 应用凭证认证失败  41000 appCredential为空
                        if (resultCode == 40002 || resultCode == 41000) {
                            SharePreferenceUtils.putString(MainActivity.this, "version", "");
                            SharePreferenceUtils.putString(MainActivity.this, Constant.appCredential, "");
                            SharePreferenceUtils.putString(MainActivity.this, Constant.userCredential, "");
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));
                            finish();
                        }
                    } else {
                        MyLogger.e("获取应用资源地址失败");
                        MyToast.show("获取应用资源地址失败");
                    }
                }
            });
        } catch (Exception e) {
            MyLogger.e(e.getMessage());
            MyToast.show(e.getMessage());
        }

    }

    /**
     * 获取人员类型
     */
    private void getData(List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> keyValueListBeanList) {
        ResourceApi personType = ResourceApiUtils.getResourceApi(MainActivity.resourceApiList, Constant.personType);
        //1 领导  2 督察  3 民警


        List<QueryBean.ParameterBean.OrderByBean> orderByList = new ArrayList<>();
        QueryBean.ParameterBean.PageBean page = new QueryBean.ParameterBean.PageBean();
        page.setPageNo(1);
        page.setPageSize(20);

        String json = JsonUtils.query(keyValueListBeanList, "idcard,type"
                , personType.getResourceId(), orderByList, page, personType.getResourceRegionalismCode());
        OkHttpUtils.post(personType.getResourceAddress(), json, QuerySuccessBean.class).compose(this.bindToLifecycle()).subscribe(new ObserverOnNext<QuerySuccessBean>() {
            @Override
            public void onNext(QuerySuccessBean querySuccessBean) {

                if (querySuccessBean.getCode().equals("200")) {
                    List list = new ArrayList();
                    list.add(new MainBean(R.mipmap.menu4, "民警维权"));
                    list.add(new MainBean(R.mipmap.menu5, "维权查询"));
                    switch (JsonUtils.queryGetFiled(querySuccessBean.getData().getDataList().get(0).getFieldValues(), "type")) {
                        case "1":
                            list.add(new MainBean(R.mipmap.menu1, "现场督察"));
                            list.add(new MainBean(R.mipmap.menu2, "汇总分析"));

                            break;
                        case "2":
                            list.add(new MainBean(R.mipmap.menu1, "现场督察"));
                            break;
                        case "3":
                            break;
                    }
                    mMainActivityAdapter.replaceData(list);
                } else {
                    MyLogger.i(querySuccessBean.getMessage());
                }
            }
        });
    }


    private void receiver(){
        //注册 登陆广播
        mReceiver = new LoginBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.clkj.mobileinspector.ACTION_LOGIN");
        intentFilter.addAction("com.clkj.mobileinspector.ACTION_LOGOUT");
        registerReceiver(mReceiver, intentFilter);
    }

    public class LoginBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            MyLogger.i("广播:"+intent.getAction());
            //登录
            if (intent.getAction().equals("com.clkj.mobileinspector.ACTION_LOGIN")) {
                MyLogger.i("登录："+intent.getAction());
                login();

            }
            //退出
            if (intent.getAction().equals("com.clkj.mobileinspector.ACTION_LOGOUT")) {
                MyLogger.i("退出："+intent.getAction());
                SharePreferenceUtils.putString(MainActivity.this, Constant.appCredential, "");
                SharePreferenceUtils.putString(MainActivity.this, Constant.userCredential, "");
            }
        }
    }
    /**
     * 登录
     */
    private void login() {
        try {
            //1获取用户凭证  IF-UA-SDK-01
            Uri uri = Uri.parse("content://com.ydjw.ua.getCredential");
            ContentResolver resolver = getContentResolver();
            Bundle params = new Bundle();
            String messageId = RandomStringUtils.getRandomString(32);//32位随机字符串
            params.putString("messageId", messageId);
            params.putString("version", "1"); //当前接口版本
            params.putString("appId", Constant.AppId);//应用 ID，由应用注册者提供，应用在 MDP 注册后生成120000000000-3-1-d74158ff4a5046609748157503252bee
            params.putString("orgId", Constant.orgId);//机构 ID，等同 regionalismCode。 120000000000
            params.putString("networkAreaCode", "3");//网络区域码，等同 networkCode。
            params.putString("packageName", "com.clkj.mobileinspector");//应用包名
            MyLogger.i("登录参数: "+ params.toString());
            Bundle bundle = resolver.call(uri, "", null, params);//call 方式调用，返回值为 Bundle 对象

            if (bundle != null) {
                String msgId = bundle.getString("messageId");
                String version = bundle.getString("version");
                int resultCode = bundle.getInt("resultCode");//0:成功, -3: 参数错误；-5: 凭证不存在 三方应用应等待统一认证去后台获取凭证
                String message = bundle.getString("message");//错误码对应的文字信息描述
                String userCredential = bundle.getString("userCredential");//用户凭证appCredential
                String appCredential = bundle.getString("appCredential");//应用凭证
                MyLogger.i("登录返回值");
                MyLogger.i("messageId：" + msgId);
                MyLogger.i("version：" + version);
                MyLogger.i("resultCode：" + resultCode);
                MyLogger.i("message：" + message);
                MyLogger.i("resultCode：" + resultCode);
                MyLogger.i("userCredential：" + userCredential);
                MyLogger.i("appCredential：" + appCredential);
                SharePreferenceUtils.putString(this, "version", version);
                SharePreferenceUtils.putString(this, Constant.appCredential, appCredential);
                SharePreferenceUtils.putString(this, Constant.userCredential, userCredential);
                dismissLoading();
                if (resultCode == 0) {
                    MyLogger.i("登录成功");

                } else {
                    MyToast.show(resultCode + message);
                }

            } else {
                MyLogger.i("获取应用凭证失败,bundle为空");
                MyToast.show("获取应用凭证失败,bundle为空");
            }
        } catch (Exception e) {
            MyLogger.i(e.getMessage());
            MyToast.show(e.getMessage());
        }
    }


}
